/**
 * WanlShop状态管理器 - 系统初始化
 * @ version 1.0.0
 **/
import config from '../../common/config/config';
export default {
	namespaced: true,
	// 储存数据
	state: {
		appStyle: {}, // APP整体样式
		appConfig: {}, // APP整体配置
		// APP链接
		appUrl: {
			api: config.appurl,
			oss: config.cdnurl
		},
		// APP整体数据
		appInfo: {
			adVersion: '0', // 广告数据版本号	拉取大版本号数据
			serviceVersion: '0' // Api数据版本号  拉取大版本号数据  用于尚未更新用户正常使用
		},
		// 广告数据
		adData: {
			openAdverts: {},
			pageAdverts: [],
			categoryAdverts: [],
			firstAdverts: [],
			otherAdverts: []
		},
		// 模块数据
		modulesData: {
			homeModules: {}, //首页模块
			categoryModules: [], //类目模块
			searchModules: [] //搜索模块
		},
		config: {
			screenshot: false,
			position: true,
			map: true
		},
		version: config.versionName,
		versionCode: config.versionCode,
		addressText: uni.getStorageSync('city'),
		cityId: uni.getStorageSync('cityid'),
		location: uni.getStorageSync('location'),
		isUpdateLocation: false,
		
		store: null
	},
	mutations: {
		setConfig(state, payload) {
			for (let i in payload) {
				for (let j in state.config) {
					if (i === j) {
						state.config[j] = payload[i];
					}
				}
			}
		},
		setState(state, payload) {
			for (let i in payload) {
				for (let j in state) {
					if (i === j) {
						state[j] = payload[i];
					}
				}
			}
		},
		setStoreInfo(state, payload) {
			state.store = payload;
			uni.setStorageSync("store", payload);
		}
	},
	// 操作数据
	actions: {
		// WanlShop 初始化，检测
		async init({state, dispatch, rootState}) {
			let userStorage = uni.getStorageSync('wanlshop:user');
			let userToken = uni.getStorageSync('token');
			let store = uni.getStorageSync('store');
			if(store) {
				rootState.common.store = store;
			}
			// uni.request({
			// 	url: '/publics/city/default',
			// 	// data: { 
			// 	// 	city: res
			// 	// },
			// 	success: (ret) => {
			// 		uni.setStorageSync('cityid', ret.data.areaid);
			// 		uni.setStorageSync('city', ret.data.name);
			// 		state.addressText = ret.data.name;
			// 		state.cityId = ret.data.areaid
			// 	}
			// })
			// dispatch('getLocation').then(res=>{
			// 	console.log(res,222222)
			// 	uni.request({
			// 	    url: '/publics/city/default',
			// 		data: {
			// 			city: res
			// 		},
			// 	    success: (ret) => {
			// 			uni.setStorageSync('cityid', ret.data.areaid);
			// 			uni.setStorageSync('city', ret.data.name);
			// 			state.addressText = ret.data.name;
			// 			state.cityId = ret.data.areaid
			// 		}
			// 	})
			// })
			uni.request({
			    url: '/wanlshop/token/check',
			    success: (res) => {
					if (res.msg === 'ok') {
						// 已经登录，刷新一个token，将原有账户赋值给状态管理器
						if (userStorage) {
							rootState.user = userStorage;
						}
						rootState.user.isLogin = true;
					}else{
						// 清除登录信息
						let user = rootState.user;
						for (let j in user) {
							user[j] = ''
						}
						rootState.user.isLogin = false;
						// 清除统计信息
						let statistics = rootState.statistics;
						for (let j in statistics) {
							for (let i in statistics[j]) {
								statistics[j][i] = 0
							}
						}
						// 从本地缓存中异步移除
						if (userStorage || userToken) {
							uni.removeStorageSync('wanlshop:user');
							uni.removeStorageSync('token');
							uni.removeStorageSync('wanlshop:statis');
							uni.removeStorageSync('lifeData');
						}
					}
					dispatch('getAds');
			    	dispatch('getServices');
			    },
			    fail: (e) => {
			    	// #ifdef APP-PLUS
			    	plus.navigator.closeSplashscreen(); //主动关闭启动图
			    	// #endif
			    }
			});
		},
		async setStore({state, commit, dispatch, rootState}, data) {
			commit('setStoreInfo', data);
		},
		async getServices({state}){
			await uni.request({
				url: '/wanlshop/common/init',
				data: {
					version: state.version
				},
				success: res => {
					// px转rpx正则表达
					for (var i = 0; i < res.data.modulesData.homeModules.item.length; i++) {
						for (var item in res.data.modulesData.homeModules.item[i].style) 
						{
							if(res.data.modulesData.homeModules.item[i].style[item])
							res.data.modulesData.homeModules.item[i].style[item] = 
							res.data.modulesData.homeModules.item[i].style[item].toString().replace(/\d*\.?\d+px/, function(match) {
								return match.replace('px', '') * 2 + 'rpx'
							})
						};
						for (var item in res.data.modulesData.homeModules.item[i].params) 
						{
							if(res.data.modulesData.homeModules.item[i].params[item])
							res.data.modulesData.homeModules.item[i].params[item] =
							res.data.modulesData.homeModules.item[i].params[item].toString().replace(/\d*\.?\d+px/, function(match) {
								return match.replace('px', '') * 2 + 'rpx'
							})
						};
					};
					// 写入全局样式
					state.appStyle = res.data.appStyle;
					// 写入模块数据
					state.modulesData = res.data.modulesData;
				}
			});
			await uni.request({
				url: '/publics/commons/getConfs',
				data: {
					version: state.version
				},
				success: (res) => {
					// 写入全局配置
					state.appConfig = res.data;
					uni.setStorageSync('appConfig', res.data);
					state.appConfig.domain = `${config.vehicleurl}/weixin`
					state.appConfig.comment_switch = `Y`
					state.appConfig.versionCode = config.versionCode
				},
			})
		},
		async getAds({state}){
			// await uni.request({
				// url: '/publics/commons/public_types',
				// data: {
				// 	version: state.version
				// },
				// success: res => {
					// if(res.data.syspopup){
					// 	uni.showModal({content: res.data.syspopup});
					// }else{
					// 	// 关闭启动图进入APP
					// 	// #ifdef APP-PLUS
					// 	setTimeout(() => {
					// 		plus.navigator.closeSplashscreen(); //主动关闭启动图
					// 	}, 100)
					// 	// #endif
					// }
					// state.adData = res.data.data;
			// 	}
			// });
			
			await uni.request({
				url: '/publics/advert/content',
				method: 'post',
				data: {
					position:'app_firing_page'
				},
				success: res => {
					state.adData.firstAdverts = res.data;
				}
			});
			await uni.request({
				url: '/publics/advert/content',
				method: 'post',
				data: {
					position:'app_open_advert'
				},
				success: res => {
					state.adData.openAdverts = res.data[0];
				}
			});
		},
		getDefaultCity() {
			
		},
		getLocation({state}) {
			var that = this
			var addressText = new Promise(function(resolve, reject){
				uni.getLocation({
					type: 'wgs84',
					geocode: true,
					highAccuracyExpireTime: 3100,
					success: mres => {
						// console.log(mres,'mresmresmres')
						let longitude = mres.longitude;
						let latitude = mres.latitude;
						state.location = {longitude:mres.longitude,latitude:mres.latitude}
						let s = uni.getStorageSync('location')
						let m = uni.getStorageSync('city')
						
						if(m && s && s.longitude == mres.longitude && s.latitude == mres.latitude && !state.isUpdateLocation) {
							resolve(m)
							return false;
						}
						console.log(mres)
						uni.setStorageSync('location', {longitude:mres.longitude,latitude:mres.latitude});
						uni.request({
							url: '/common/getLocationInfo',
							data: {
								key: config.amapkey,
								location: mres.longitude + ',' + mres.latitude,
								output: 'JSON'
							},
							success: res => {
								let resData = res.data
								let city = resData.regeocode.formatted_address
								let citys = resData.regeocode.addressComponent.city
								let province = resData.regeocode.addressComponent.province
								if (res.statusCode == 200) {
									citys = typeof citys == 'string' ? citys : province
									uni.setStorageSync('formatted_address', city);
									resolve(citys)
								}
							},
							fail: error => {
								resolve('')
							}
						});
					},
					
					fail: error => {
						console.log(error)
					}
				})
			})
			return addressText;
		}
	}
};